package spring.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import spring.demo.bean.User;
import spring.demo.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
//跳转登录页面
    @RequestMapping("login")
    public String login(){
        return "login";
    }
    //返回全部页面
    @RequestMapping("/all")
    public String loginAll(Model model){
        List<User> all =this.userService.findAll();
        model.addAttribute("all",all);
        return "all";
    }
    //控制器返回error界面
    @RequestMapping("/error1")
    public String error1(){
        return "error";
    }
    //控制器根据用户请求删除id
    @RequestMapping("delete/{id}")
    public ModelAndView delete(@PathVariable int id){
        userService.deleteById(id);
        ModelAndView mav = new ModelAndView("redirect:/all");
        return mav;
    }
    //跳转请求界面--add新增界面
    @RequestMapping("Add1")
    public  ModelAndView Add1(){
        return new ModelAndView("add");
    }
    //一个方法（action） 用于新增数据--
    @RequestMapping("AddUser")
    public ModelAndView AddUser(User user){
        userService.add(user);
        ModelAndView mav = new ModelAndView("redirect:/login");
        return mav;
    }
    //也是一个方法 用于验证登录的账号密码
    @RequestMapping(value = "loginPage", method = {RequestMethod.GET,RequestMethod.POST})
    public String useCon(HttpServletRequest request, HttpSession session){
        String username= request.getParameter("username");
        String password=request.getParameter("password");
        String tname = userService.login(username,password);
        if (tname==null){
            return "redirect:/error1";
        }else {
            return "redirect:/all";
        }

    }

}
